package org.kisekiproject.course {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import org.kisekiproject.events.KisekiEvent;

	/**
	 * A course group.
	 */
	public class CourseGroup extends EventDispatcher {

		public static var CONTENT_CHANGE:String="contentChange";

		private var _id:String;
		private var _pages:Array;

		/**
		 * Constructor.
		 */
		public function CourseGroup() {
			_pages=new Array();
		}

		/**
		 * Parse.
		 * Doesn't parse contained page nodes.
		 */
		public function parse(source:XML):void {
			_id=String(source.@id);
		}

		/**
		 * Add a page to the group.
		 */
		public function addPage(page:CoursePage):void {
			_pages.push(page);

			page.addEventListener(KisekiEvent.OUTPUT_CHANGE,onOutputChange);
		}

		/**
		 * Output change
		 */
		protected function onOutputChange(event:Event):void {
			notifyContentChange();
		}
		
		/**
		 * Get id.
		 */
		public function get id():String {
			return _id;
		}

		/**
		 * Get pages.
		 */
		public function get pages():Array {
			return _pages;
		}

		/**
		 * Get current visible index.
		 */
		public function get visibleIndex():int {
			for (var i:int=0; i<pages.length; i++)
				if (CoursePage(pages[i]).visible)
					return i;

			return -1;
		}

		/**
		 * Set visible index.
		 */
		public function set visibleIndex(value:int):void {
			if (value>=pages.length)
				value=pages.length-1;

			if (value<0)
				value=0;

			for (var i:int=0; i<pages.length; i++)
				CoursePage(pages[i]).visible=(value==i);

			notifyContentChange();
		}

		/**
		 * Content change.
		 */
		public function notifyContentChange():void {
//			trace("content change in group........");
			dispatchEvent(new Event(CONTENT_CHANGE));
		}

		/**
		 * Get the ojbect that is exposed to the course.
		 */
		public function get exposed():Object {
			var current:int=-1;
			var currentPage:Object=new Object();

			for (var i:int=0; i<pages.length; i++)
				if (CoursePage(pages[i]).visible) {
					currentPage=CoursePage(pages[i]).displayObject
					current=i;
				}

			return {
				previousPossible: pages.length>0?!CoursePage(pages[0]).visible:false,
				nextPossible: pages.length>0?!CoursePage(pages[pages.length-1]).visible:false,
				length: pages.length,
				current: current,
				currentPage: currentPage
			}
		}
	}
}